<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Autocomplete TextBox</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.3/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
    <script src="https://code.jquery.com/ui/1.13.3/jquery-ui.js"></script>
    <script>
        $(document).ready(function() {
            var textboxId = 'txtStockCode';
            var textbox = $('#txtStockCode');
            var history = localStorage.getItem(textboxId) ? JSON.parse(localStorage.getItem(textboxId)) : [];

            // Initialize autocomplete with empty array or history if available
            textbox.autocomplete({
                source: history
            });

            $('#btnSearch').click(function(e) {
                e.preventDefault();
                var input = textbox.val();

                // Add new input to history if it's not empty and not already in history
                if (input && !history.includes(input)) {
                    history.unshift(input);
                    localStorage.setItem(textboxId, JSON.stringify(history));
                }

                // Update the source of the autocomplete to include the new history
                textbox.autocomplete({
                    source: history
                });
            });
        });
    </script>
</head>

<body>
    <input id="txtStockCode" type="text" />
    <button id="btnSearch">查询</button>
</body>

</html>